package com.example.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.CoustomException;
import com.example.demo.dto.SetmealDto;
import com.example.demo.entity.Setmeal;
import com.example.demo.entity.SetmealDish;
import com.example.demo.mapper.SetmealMapper;
import com.example.demo.service.SetmealDishService;
import com.example.demo.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    SetmealDishService setmealDishService;
    /*
    新增套餐，同时保证菜品的关联关系
     */
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息，操作setmeal,执行insert操作
        this.save(setmealDto);
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert语句
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        log.info("添加菜品1"+setmealDto.getId());
        log.info("添加菜品2"+setmealDto.getIdType());
        setmealDishes=setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        log.info("添加菜品"+setmealDishes);
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert语句
        setmealDishService.saveBatch(setmealDishes);
    }
//删除套餐同时删除套餐的关联数据
    @Override
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.in(Setmeal::getId,ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(lambdaQueryWrapper);
        if(count>0){//如果不能删除，抛出一个业务异常
            throw  new CoustomException("套餐正在售卖中，不能删除");
        }

        //如果可以删除，先删除套餐表中的数据
        this.removeByIds(ids);
        //在删除关系表中的数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper1);
    }
}
